package com.jzo2o.orders.manager.listener;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jzo2o.api.trade.enums.PayChannelEnum;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.orders.base.enums.OrderPayStatusEnum;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.manager.service.IOrdersManagerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * \* User: chy
 * \* Date: 2025/10/8  18:52
 * \* Description:订单支付成功通知
 * \
 */
@Component
@Slf4j
public class PaySuccessNotifyListener {

    @Autowired
    private IOrdersManagerService ordersManagerService;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS, durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchanges.TRADE),
            key = MqConstants.RoutingKeys.TRADE_UPDATE_STATUS
    ))
    public void paySuccessNotify(String msg) {
        log.info("订单支付成功通知：{}", msg);

        // 将msg转为json对象,通过hutool工具包
        JSONObject jsonMsg = JSONUtil.parseObj(msg);
        // 获取订单id
         String ordersId =jsonMsg.get("productOrderNo")+ "";
         // 查询订单
        Orders orders = ordersManagerService.getById(ordersId);
        if (orders == null) {
            log.info("当前订单不存在：{}", msg);
            return;
        }
        // 更新订单支付状态
        orders.setPayStatus(OrderPayStatusEnum.PAY_SUCCESS.getStatus());
        // 更新订单状态
        orders.setOrdersStatus(OrderStatusEnum.DISPATCHING.getStatus());
        // 支付时间
        orders.setPayTime(LocalDateTime.now());
        // 支付渠道
        orders.setTradingChannel(jsonMsg.get("tradingChannel")+ "");
        // 支付单号
//        orders.setTradingOrderNo( Long.parseLong(jsonMsg.get("tradingOrderNo")+ ""));
        ordersManagerService.updateById( orders);

    }
}
